package tags.templates;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import main.PMF;
import main.UserView;

import DBClasses.Game;
import DBClasses.Game.PriceTypes;
import DBClasses.GameComment;
import DBClasses.GameType;
import DBClasses.ItemPair;
import DBClasses.User;

public class CatItem extends TagSupport
{
	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unchecked")
	public int doStartTag() throws JspException
	{
		String result = "";
		long id = (long) -1;
		boolean valid_gt = true;
		PersistenceManager manager = PMF.get().getPersistenceManager();
		List<Game> gts = null;
		try
		{
			if (pageContext.getRequest().getParameter("id") != null
					&& pageContext.getRequest().getParameter("id") != "0")
			{
				id = Long
						.parseLong(pageContext.getRequest().getParameter("id"));
				gts = (List<Game>) manager.newQuery(
						"select from " + Game.class.getName() + " where id == "
								+ id).execute();
				valid_gt = !(gts == null || gts.size() <= 0);
			}
		} catch (Exception ex)
		{
			valid_gt = false;
		}
		if (valid_gt)
		{
			SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm");
			Game game = gts.get(0);
			String cat = "0";
			List<GameType> gs = (List<GameType>) manager.newQuery(
					"select from " + GameType.class.getName()
							+ " where name == '" + game.getGameType() + "'")
					.execute();
			if (gs != null && gs.size() > 0)
				cat = gs.get(0).getId().toString();
			String img_str = "";
			if (game.getImg() != "")
				img_str = "<img alt=\"\" src=\"/egs_img?max=200&img_id="
						+ game.getImg() + "\" class=\"news_icon\"/>";
			result = "<div class=\"news_block\">"
					+ img_str
					+ "<div class=\"news_header\">"
					+ "<a href=\"/items.jsp?id="
					+ game.getId()
					+ "\">"
					+ game.getName()
					+ "</a>"
					+ "<div class=\"news_inf\">"
					+ sdf.format(game.getAddDate())
					+ ", "
					+ game.getAdder()
					+ "</div>"
					+ "<div class=\"news_inf\" style=\"color: #0099FF\">"
					+ "Жанр: <a class=\"cats_data\" href=\"/categories.jsp?id="
					+ cat
					+ "\">"
					+ game.getGameType()
					+ "</a>"
					+ "</div>"
					+ "<div class=\"cats_inf\">"
					+ "Цена: <a class=\"cats_data\">"
					+ game.getPrice(PriceTypes.Rubl)
					+ "</a>"
					+ "</div>"
					+ "<div class=\"cats_inf\" style=\" height:30px\">"
					+ "<a class=\"log_reg_btn top_text_stl\" id=\"buy_btn\" style=\"width:180px\" "
					+ "onclick=\"SubmitBuy('/buy?id=" + +game.getId()
					+ "');\">Добавить в корзину" + "</a></div>" + "</div>"
					+ game.getDescription();

			List<ItemPair> full_it_prs = (List<ItemPair>) manager.newQuery(
					"select from " + ItemPair.class.getName()
							+ " where id1 == " + game.getId()).execute();
			List<ItemPair> it_prs = (List<ItemPair>) manager.newQuery(
					"select from " + ItemPair.class.getName()
							+ " where id2 == " + game.getId()).execute();
			String top_string = "";
			List<Long> tops = new ArrayList<Long>();
			for (int i = 0; i < 5; i++)
			{
				Long max = 0L;
				int ind = 0;
				Boolean finded = false;
				ItemPair fd = null;
				for (ItemPair itemPair : full_it_prs)
				{
					ind++;
					if (itemPair.getCount() >= max)
					{
						if (!tops.contains(itemPair.getId()))
						{
							finded = true;
							max = itemPair.getCount();
							fd = itemPair;
						}
					}
				}
				for (ItemPair itemPair : it_prs)
				{
					ind++;
					if (itemPair.getCount() >= max)
					{
						if (!tops.contains(itemPair.getId()))
						{
							finded = true;
							max = itemPair.getCount();
							fd = itemPair;
						}
					}
				}
				if (finded)
				{
					tops.add(fd.getId());
					Long top_id = -1L;
					if (fd.get1id().equals(id))
						top_id = fd.get2id();
					else
						top_id = fd.get1id();
					List<Game> top_gts = (List<Game>) manager.newQuery(
							"select from " + Game.class.getName()
									+ " where id == " + top_id).execute();
					if (top_gts.size() > 0)
						top_string += "<a class=\"cats_data\" href=\"items.jsp?id="
								+ top_id
								+ "\">"
								+ top_gts.get(0).getName()
								+ "</a>" + "   ";
				}
			}
			if (tops.size() > 0)
				result += "<div class=\"news_inf\" style=\"margin-top:10px;margin-left:10px; color: #0099FF\">С этой игрой также покупают: "
						+ top_string + "</div>";
			result += "</div>";

			if(game.getScrns().size()>0)
			{
				result+="<div class = \"cmnt_header\">Скриншоты</div>";
				result+="<div id=\"scr_container\" style=\"width:100%; height:250px\">";
				for (String scr : game.getScrns())
				{
					result+="<a target=\"_blank\" href =\"/egs_img?img_id="
							+ scr+"\"><img class = \"scr\" alt=\"\" src=\"/egs_img?max=200&img_id="
							+ scr + "\" class=\"news_icon\"/></img></a>";
				}
				result+="</div>";
			}
			
			List<GameComment> cmnts = (List<GameComment>) manager.newQuery(
					"select from " + GameComment.class.getName()
							+ " where game == " + game.getId()).execute();
			if (cmnts != null && cmnts.size() > 0)
			{
				result += "<div class=\"cmnt_header\">Комментарии</div>";
				String cmnts_str = "";
				for (GameComment gameComment : cmnts)
				{
					cmnts_str = "<div class=\"cmnt_block\">"
							+ "<div class=\"news_inf\">"
							+ gameComment.getAuthor() + ", "
							+ sdf.format(gameComment.getPostDate()) + "</div>"
							+ gameComment.getText() + "</div>" + cmnts_str;
				}
				result += cmnts_str;
			}
		} else
		{
			result = "<div style=\"margin:20px\">Такой игры пока нет...</div>";
		}

		try
		{
			pageContext.getOut().flush();
			pageContext.getOut().print(result);
		} catch (Exception ex)
		{
			throw new JspException(ex.getMessage());
		}
		manager.close();
		return SKIP_BODY;
	}

	public void release()
	{
	}
}
